package com.payment.controller.payment;

import com.payment.utils.WxJSUtil;
import com.payment.utils.payment.WxPayConstants;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(description = "微信公众号内扫一扫")
/**
 * 1，微信公众号内扫一扫接口：
 *
 * 2，适用于新的客户：最新版的的领科 H5 在公众号内商城扫一扫功能；
 *
 * @author lm
 * @date 2019/11/06
 */
public class WeixinSaoController {

    private static Logger logger = Logger.getLogger(WeixinSaoController.class);

    @GetMapping(value = "/weixinsao")
    @ResponseBody
    @CrossOrigin
    public String scan(Model model, HttpServletRequest request) {

        //动态获取调用jssdk扫一扫功能的url
        String jsonString = "";
        try {
            String reqUrl = request.getParameter("reqUrl");
            String jsUrl = reqUrl.toString();

            logger.debug("微信扫描请求的链接是：" + request.getRequestURL() + "?" + request.getQueryString() + ";请求的url是：" + reqUrl + ";编译之后的链接：" + jsUrl);

            Map<String, String> ret = WxJSUtil.sign(jsUrl);

            String url1 = ret.get("url");

            String timestamp = ret.get("timestamp");

            String nonceStr = ret.get("nonceStr");

            String signature = ret.get("signature");

            for (Map.Entry entry : ret.entrySet()) {
                logger.debug("扫描解析的key及对应的value：" + entry.getKey() + "=" + entry.getValue());
                model.addAttribute(entry.getKey().toString(), entry.getValue());
            }

            HashMap map = new HashMap();
            map.put("appId", WxPayConstants.APPID);
            map.put("timestamp", timestamp);
            map.put("nonceStr", nonceStr);
            map.put("signature", signature);

            JSONObject jsonObject = JSONObject.fromObject(map);
            // 3、将json对象转化为json字符串
            jsonString = jsonObject.toString();
            logger.debug("返回的json是：" + jsonString);
            return jsonString;

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
}

